package com.sh.util;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;

public  class QiNiuFileUtil {
    //设置好账号的ACCESS_KEY和SECRET_KEY
    private static final String ACCESS_KEY = "1_OeHyPTYVyRBVzRDmNJGpJ3WWj6kwr5QCgHyvy7"; //这两个登录七牛 账号里面可以找到
    private static final String SECRET_KEY = "RP3h-yZf_N4jqxe5yhwZJaXinTAgh-_sdwr0weEI";
    //要上传的空间
    private static final String bucketname = "weihaujunspce"; //对应要上传到七牛上 你的那个路径（自己建文件夹 注意设置公开）
     //MultipartFile
    public static Boolean  uploadFile(File file, String fileName) throws IOException {
        //密钥配置
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

        /*Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);*/
        //创建上传对象
        Configuration cfg = new Configuration(Zone.autoZone());  //zong1() 代表华北地区
       // UploadManager uploadManager = new UploadManager(cfg);

        // //设置断点续传文件进度保存目录
        String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), bucketname).toString();
        FileRecorder fileRecorder = new FileRecorder(localTempDir);
        UploadManager uploadManager = new UploadManager(cfg, fileRecorder);


      /*  //上传自定义参数，自定义参数名称需要以 x:开头
        StringMap params = new StringMap();
        params.put("x:fname","123.jpg");
        params.put("x:age",20);
        //上传策略
        StringMap policy = new StringMap();
//自定义上传后返回内容，返回自定义参数，需要设置 x:参数名称，注意下面
        policy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"fname\":\"$(x:fname)\",\"age\",$(x:age)}");
//生成上传token
        String upToken = auth.uploadToken(bucketname, "four.gif", 3600, policy);
        Response put = uploadManager.put(new File("11.gif"), "four.gif", upToken, params, null, false);*/
        //简单上传，使用默认策略，只需要设置上传的空间名就可以了
        try {
            //通过文件上传文件哎，也可以通过字符串上传文件
           // Response put = uploadManager.put(file, "1", auth.uploadToken(bucketname));
           /* Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);*/
            //调用put方法上传
            //通过字节上传文件
            FileInputStream inputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(inputStream));
            Response res = uploadManager.put(multipartFile.getBytes(), fileName, auth.uploadToken(bucketname));
           // String path = QiniuUtils.uploadQNImg(inputStream, PictureUtil.getRandomFileName()); // KeyUtil.genUniqueKey()生成图片的随机名
            //System.out.print("七牛云返回的图片链接:" + path);
            //return path;

            //打印返回的信息
            System.out.println(res.bodyString());
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
                return false;
            }
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

